<template>
  <div class="chess-game-page">
    <el-breadcrumb separator="/" style="margin-bottom: 16px;">
      <el-breadcrumb-item to="/home">{{ $t('menu.home') }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ $t('chess.title') }}</el-breadcrumb-item>
    </el-breadcrumb>
    
    <el-card class="game-card">
      <div class="game-layout">
        <!-- 左侧控制面板 -->
        <div class="game-panel">
          <!-- 游戏状态 -->
          <el-card class="control-card">
            <template #header>
              <div class="card-header">{{ $t('chess.gameStatus') }}</div>
            </template>
            <div class="game-status">
              <div class="status-item">
                <span class="label">{{ $t('chess.currentPlayer') }}：</span>
                <span :class="`player-${currentPlayer}`">
                  {{ currentPlayer === 'red' ? $t('chess.redPlayer') : $t('chess.blackPlayer') }}
                </span>
              </div>
              <div class="status-item">
                <span class="label">{{ $t('chess.gameStatus') }}：</span>
                <span class="status">{{ getStatusText() }}</span>
              </div>
              <div class="status-item">
                <span class="label">{{ $t('chess.roundCount') }}：</span>
                <span class="count">{{ Math.ceil(gameInfo.moveCount / 2) }}</span>
              </div>
              <div class="status-item">
                <span class="label">{{ $t('chess.gameMode') }}：</span>
                <span class="status">{{ getModeText() }}</span>
              </div>
            </div>
          </el-card>

          <!-- 控制按钮 -->
          <el-card class="control-card">
            <template #header>
              <div class="card-header">{{ $t('chess.gameControl') }}</div>
            </template>
            <div class="control-buttons">
              <el-button type="success" @click="startNewGame" :icon="Refresh">
                {{ $t('chess.newGame') }}
              </el-button>
              <el-button 
                type="warning" 
                @click="undoMove" 
                :disabled="!gameInfo.canUndo || gameStatus !== 'playing'"
                :icon="Back"
              >
                {{ $t('chess.undo') }}
              </el-button>
              <el-button 
                type="danger" 
                @click="resign" 
                :disabled="gameStatus !== 'playing'"
                :icon="CloseBold"
              >
                {{ $t('chess.resign') }}
              </el-button>
              <el-button type="primary" @click="showSettings = true" :icon="Setting">
                {{ $t('common.settings') }}
              </el-button>
            </div>
          </el-card>

          <!-- AI设置 -->
          <el-card class="control-card" v-if="gameMode === 'human_vs_ai'">
            <template #header>
              <div class="card-header">{{ $t('chess.aiSettings') }}</div>
            </template>
            <div class="ai-settings">
              <div class="setting-item">
                <span class="setting-label">{{ $t('chess.aiDifficulty') }}：</span>
                <el-select v-model="aiDifficultyLevel" @change="onDifficultyChange" size="small">
                  <el-option :label="$t('chess.difficultyBeginner')" :value="1" />
                  <el-option :label="$t('chess.difficultyEasy')" :value="2" />
                  <el-option :label="$t('chess.difficultyMedium')" :value="3" />
                  <el-option :label="$t('chess.difficultyHard')" :value="4" />
                  <el-option :label="$t('chess.difficultyExpert')" :value="5" />
                  <el-option :label="$t('chess.difficultyMaster')" :value="6" />
                  <el-option :label="$t('chess.difficultyGrandmaster')" :value="7" />
                </el-select>
              </div>
              <div class="setting-item">
                <span class="setting-label">{{ $t('chess.aiSide') }}：</span>
                <el-select v-model="aiColor" @change="onAIColorChange" size="small">
                  <el-option :label="$t('chess.blackPlayer')" value="black" />
                  <el-option :label="$t('chess.redPlayer')" value="red" />
                </el-select>
              </div>
              <div v-if="isAIThinking" class="ai-thinking">
                <span class="thinking-text">🤔 {{ $t('chess.aiThinking') }}</span>
              </div>
            </div>
          </el-card>

          <!-- 被吃棋子 -->
          <el-card class="control-card captured-pieces">
            <template #header>
              <div class="card-header">{{ $t('chess.capturedPieces') }}</div>
            </template>
            <div class="captured-section">
              <div class="captured-group">
                <div class="group-title">{{ $t('chess.redPlayer') }} ({{ capturedPieces.red.length }})</div>
                <div class="pieces-list">
                  <span 
                    v-for="(piece, index) in capturedPieces.red" 
                    :key="`red-${index}`"
                    class="captured-piece piece-red"
                  >
                    {{ piece.name }}
                  </span>
                  <span v-if="capturedPieces.red.length === 0" class="no-pieces">{{ $t('chess.none') }}</span>
                </div>
              </div>
              <div class="captured-group">
                <div class="group-title">{{ $t('chess.blackPlayer') }} ({{ capturedPieces.black.length }})</div>
                <div class="pieces-list">
                  <span 
                    v-for="(piece, index) in capturedPieces.black" 
                    :key="`black-${index}`"
                    class="captured-piece piece-black"
                  >
                    {{ piece.name }}
                  </span>
                  <span v-if="capturedPieces.black.length === 0" class="no-pieces">{{ $t('chess.none') }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 中间棋盘区域 -->
        <div class="board-area">
          <ChessBoard
            :board="board"
            :current-player="currentPlayer"
            :game-status="gameStatus"
            :move-count="gameInfo.moveCount"
            :selected-position="selectedPosition"
            :valid-moves="validMoves"
            :last-move="lastMove"
            :check-positions="checkPositions"
            :show-move-hints="showMoveHints"
            :disabled="!canInteract"
            @cell-click="handleCellClick"
            @piece-select="handlePieceSelect"
            @move="handleMove"
          />
        </div>

        <!-- 右侧历史记录 -->
        <div class="history-panel">
          <el-card class="history-card">
            <template #header>
              <div class="card-header">{{ $t('chess.moveHistory') }}</div>
            </template>
            <div class="move-history">
              <div 
                v-for="(move, index) in moveHistory" 
                :key="index"
                :class="['move-item', { 'current-move': index === moveHistory.length - 1 }]"
              >
                <span class="move-number">{{ Math.floor(index / 2) + 1 }}.</span>
                <span class="move-text">{{ formatMove(move) }}</span>
              </div>
              <div v-if="moveHistory.length === 0" class="no-moves">
                {{ $t('chess.noMoves') }}
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>

    <!-- 设置对话框 -->
    <el-dialog v-model="showSettings" title="游戏设置" width="500px">
      <el-form label-width="100px">
        <el-form-item label="游戏模式">
          <el-radio-group v-model="gameMode">
            <el-radio label="human_vs_human">人机对战</el-radio>
            <el-radio label="human_vs_ai">人机对战</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="显示提示">
          <el-switch v-model="showMoveHints" />
        </el-form-item>
        <el-form-item label="音效">
          <el-switch v-model="soundEnabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSettings = false">取消</el-button>
        <el-button type="primary" @click="applySettings">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Refresh, Back, Setting, CloseBold } from '@element-plus/icons-vue';
import { useI18n } from 'vue-i18n';
import ChessBoard from '@/components/chess/ChessBoard.vue';
import { ChessEngine } from '@/utils/chess/engine/ChessEngine.js';
import { ChessAI } from '@/utils/chess/ai/ChessAI.js';
import { GAME_STATUS, GAME_MODE, AI_DIFFICULTY } from '@/utils/chess/constants/gameConfig.js';
import { COLORS } from '@/utils/chess/constants/pieces.js';

const { t } = useI18n();

// 游戏引擎和AI
const chessEngine = new ChessEngine();
let chessAI = null;

// 游戏状态
const board = ref([]);
const currentPlayer = ref('red');
const gameStatus = ref(GAME_STATUS.PLAYING);
const moveHistory = ref([]);
const capturedPieces = reactive({
  red: [],
  black: []
});
const lastMove = ref(null);

// 交互状态
const selectedPosition = ref(null);
const validMoves = ref([]);
const checkPositions = ref([]);

// 游戏设置
const gameMode = ref(GAME_MODE.HUMAN_VS_AI);
const aiColor = ref('black');
const aiDifficultyLevel = ref(3);
const showMoveHints = ref(true);
const soundEnabled = ref(false);
const showSettings = ref(false);

// AI状态
const isAIThinking = ref(false);

// 游戏信息
const gameInfo = computed(() => chessEngine.getGameInfo());

// 计算是否可以交互
const canInteract = computed(() => {
  if (gameStatus.value !== GAME_STATUS.PLAYING) return false;
  if (gameMode.value === GAME_MODE.HUMAN_VS_AI) {
    return currentPlayer.value !== aiColor.value && !isAIThinking.value;
  }
  return true;
});

// 初始化游戏
onMounted(() => {
  initGame();
});

// 监听当前玩家变化，触发AI移动
watch(currentPlayer, (newPlayer) => {
  if (gameMode.value === GAME_MODE.HUMAN_VS_AI && 
      newPlayer === aiColor.value && 
      gameStatus.value === GAME_STATUS.PLAYING) {
    setTimeout(() => {
      makeAIMove();
    }, 500);
  }
});

function initGame() {
  chessEngine.reset();
  updateGameState();
  
  // 初始化AI
  const difficulty = getDifficultyByLevel(aiDifficultyLevel.value);
  chessAI = new ChessAI(difficulty);
  
  // 如果AI先手
  if (gameMode.value === GAME_MODE.HUMAN_VS_AI && aiColor.value === 'red') {
    setTimeout(() => {
      makeAIMove();
    }, 1000);
  }
}

function updateGameState() {
  board.value = chessEngine.getBoard();
  currentPlayer.value = chessEngine.getCurrentPlayer();
  gameStatus.value = chessEngine.getGameStatus();
  moveHistory.value = chessEngine.getMoveHistory();
  const captured = chessEngine.getCapturedPieces();
  capturedPieces.red = captured[COLORS.RED] || [];
  capturedPieces.black = captured[COLORS.BLACK] || [];
  lastMove.value = chessEngine.getLastMove();
  
  // 更新将军位置
  updateCheckPositions();
}

function updateCheckPositions() {
  checkPositions.value = [];
  // 这里可以添加检测将军位置的逻辑
}

function handleCellClick(data) {
  if (!canInteract.value) return;
  
  const { row, col, piece } = data;
  
  // 如果已选中棋子，并且点击有效移动位置
  if (selectedPosition.value) {
    const isValidMove = validMoves.value.some(
      move => move.row === row && move.col === col
    );
    
    if (isValidMove) {
      // 不在这里执行移动，让 handleMove 统一处理
      // executeMove(selectedPosition.value, { row, col });
      return; // ChessBoard 会发出 move 事件
    } else {
      // 点击其他位置，取消选择或选择新棋子
      if (piece && piece.color === currentPlayer.value) {
        selectPiece({ row, col, piece });
      } else {
        clearSelection();
      }
    }
  } else {
    // 选择棋子
    if (piece && piece.color === currentPlayer.value) {
      selectPiece({ row, col, piece });
    }
  }
}

function handlePieceSelect(data) {
  selectPiece(data);
}

function handleMove(moveData) {
  // 统一在这里处理所有移动
  executeMove(moveData.from, moveData.to);
}

function selectPiece(data) {
  const { row, col } = data;
  selectedPosition.value = { row, col };
  validMoves.value = chessEngine.getValidMoves({ row, col });
}

function clearSelection() {
  selectedPosition.value = null;
  validMoves.value = [];
}

function executeMove(from, to) {
  const result = chessEngine.makeMove(from, to);
  
  if (result.success) {
    clearSelection();
    updateGameState();
    
    // 检查游戏是否结束
    if (gameStatus.value !== GAME_STATUS.PLAYING) {
      handleGameEnd();
    }
  } else {
    // 使用国际化的错误消息
    ElMessage.warning(result.message || t('chess.invalidMove'));
  }
}

function makeAIMove() {
  if (gameStatus.value !== GAME_STATUS.PLAYING) return;
  
  isAIThinking.value = true;
  
  setTimeout(() => {
    try {
      // 传递移动历史给AI，让它避免愚蠢的重复移动
      const bestMove = chessAI.getBestMove(board.value, currentPlayer.value, moveHistory.value);
      
      if (bestMove) {
        executeMove(bestMove.from, bestMove.to);
      } else {
        ElMessage.warning(t('chess.aiNoValidMove'));
      }
    } catch (error) {
      console.error('AI移动错误:', error);
      ElMessage.error(t('chess.aiMoveFailed'));
    } finally {
      isAIThinking.value = false;
    }
  }, 300);
}

function startNewGame() {
  ElMessageBox.confirm(t('chess.confirmRestart'), t('chess.confirmTitle'), {
    confirmButtonText: t('common.confirm'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  }).then(() => {
    initGame();
    ElMessage.success(t('chess.gameReset'));
  }).catch(() => {});
}

function undoMove() {
  const result = chessEngine.undoMove();
  if (result.success) {
    // 如果是人机对战，需要撤销两步
    if (gameMode.value === GAME_MODE.HUMAN_VS_AI) {
      chessEngine.undoMove();
    }
    updateGameState();
    clearSelection();
    ElMessage.success(t('chess.undoSuccess'));
  } else {
    ElMessage.warning(result.message);
  }
}

function resign() {
  ElMessageBox.confirm(t('chess.confirmRestart'), t('chess.confirmTitle'), {
    confirmButtonText: t('common.confirm'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  }).then(() => {
    gameStatus.value = GAME_STATUS.RESIGN;
    const winner = currentPlayer.value === 'red' ? t('chess.blackPlayer') : t('chess.redPlayer');
    ElMessage.info(`${winner}${t('chess.statusResign')}`);
  }).catch(() => {});
}

function handleGameEnd() {
  let message = '';
  switch (gameStatus.value) {
    case GAME_STATUS.CHECKMATE:
      const winner = currentPlayer.value === 'red' ? '黑方' : '红方';
      message = `${winner}获胜（将死）`;
      break;
    case GAME_STATUS.STALEMATE:
      message = '和棋（困毙）';
      break;
    case GAME_STATUS.DRAW:
      message = '和棋';
      break;
    default:
      return;
  }
  
  setTimeout(() => {
    ElMessageBox.alert(message, '游戏结束', {
      confirmButtonText: '确定',
      callback: () => {}
    });
  }, 500);
}

function onDifficultyChange(level) {
  const difficulty = getDifficultyByLevel(level);
  if (chessAI) {
    chessAI.setDifficulty(difficulty);
  }
  ElMessage.success(`AI难度已设置为：${difficulty.name}`);
}

function onAIColorChange() {
  ElMessage.info('请开始新游戏以应用AI执子颜色');
}

function applySettings() {
  showSettings.value = false;
  ElMessage.success('设置已保存');
}

function getDifficultyByLevel(level) {
  const difficultyMap = {
    1: AI_DIFFICULTY.BEGINNER,
    2: AI_DIFFICULTY.EASY,
    3: AI_DIFFICULTY.MEDIUM,
    4: AI_DIFFICULTY.HARD,
    5: AI_DIFFICULTY.EXPERT,
    6: AI_DIFFICULTY.MASTER,
    7: AI_DIFFICULTY.GRANDMASTER
  };
  return difficultyMap[level] || AI_DIFFICULTY.MEDIUM;
}

function getStatusText() {
  const statusMap = {
    playing: t('chess.statusPlaying'),
    checkmate: t('chess.statusCheckmate'),
    stalemate: t('chess.statusStalemate'),
    draw: t('chess.statusDraw'),
    resign: t('chess.statusResign')
  };
  return statusMap[gameStatus.value] || t('chess.statusUnknown');
}

function getModeText() {
  return gameMode.value === GAME_MODE.HUMAN_VS_AI ? t('chess.modeHumanVsAI') : t('chess.modeHumanVsHuman');
}

function formatMove(move) {
  if (!move || !move.piece) return '';
  const fromPos = `(${move.from.row},${move.from.col})`;
  const toPos = `(${move.to.row},${move.to.col})`;
  return `${move.piece.name} ${fromPos} → ${toPos}`;
}
</script>

<style scoped src="@/styles/chess/ChessGame.scss"></style>

